import { useEffect, useState } from 'react';
import Map, { Marker } from 'react-map-gl/maplibre';
import 'maplibre-gl/dist/maplibre-gl.css';
import { getClusterPoint, getJHDBg, getMockPoint, getSize, isLocal, mapStyle } from '@/utils';
import BigImg from './BigImg';

const DEFZOOM = 16.3; // 9
// const DEFZOOM = 9; // 9

export default function DetialMap({
  longitude = -1,
  latitude = -1,
  NUM = 100,
  setImgIndex,
  imgUrl,
  setImgUrl,
}: any) {
  const [points, setPoints] = useState<any>([]);
  const [viewState, setViewState] = useState<any>({
    longitude,
    latitude,
    zoom: DEFZOOM,
  });
  const [clusters, setClusters] = useState<any>([]); // 聚合点

  useEffect(() => {
    console.log('=====latitude: ', latitude, longitude, NUM);
    if (longitude === -1 || latitude === -1) return;
    setPoints(getMockPoint(NUM, longitude, latitude));
  }, [longitude, latitude, NUM]);

  // 计算聚合点
  useEffect(() => {
    if (longitude === -1 || latitude === -1 || points?.length === 0) return;
    const _clusters = getClusterPoint(points, viewState.zoom);
    setClusters(_clusters);
  }, [longitude, points, viewState.zoom]);

  // 点点击
  function pointClick(cluster: any, i: number) {
    console.log('点点击');
    console.log('cluster.count: ', cluster);
    // 点击聚合点时，可以展开显示所有点
    if (cluster.count > 1) {
      // coordinates
      setViewState({
        longitude: cluster.coordinates[0],
        latitude: cluster.coordinates[1],
        zoom: DEFZOOM,
      });
      return;
    }
    setImgIndex(i);
  }

  // 渲染聚合点
  const renderClusters = () => {
    if (!clusters || clusters.length === 0) return null;
    return clusters.map((cluster: any, i: number) => {
      // 根据聚合点数量确定大小和颜色
      const color = getJHDBg(cluster?.points);
      return (
        <Marker
          key={cluster.id}
          longitude={cluster.coordinates[0]}
          latitude={cluster.coordinates[1]}
          anchor="center"
        >
          <div
            className="flex items-center justify-center cursor-pointer"
            style={{
              width: `${getSize(cluster.count)}px`,
              height: `${getSize(cluster.count)}px`,
              borderRadius: '50%',
              background: color,
              color: 'white',
              transition: 'transform 0.2s ease',
              border: '2px solid white',
              boxSizing: 'border-box',
              fontSize: '12px',
            }}
            onClick={() => pointClick(cluster, i)}
          >
            {cluster?.count > 10 ? cluster.count : ''}
          </div>
        </Marker>
      );
    });
  };

  return (
    <div className={`detailMapWrap ${imgUrl && 'showBigMap'}`}>
      {imgUrl && <BigImg imgUrl={imgUrl} setImgUrl={setImgUrl} />}

      <div className="mapWrap">
        <div className="zoomwrap">
          zoom: {viewState.zoom.toFixed(1)}
          {isLocal() && `,点数: ${clusters?.length} `}
        </div>
        <Map
          {...viewState}
          onMove={(evt) => setViewState(evt.viewState)}
          style={{ width: '100%', height: 'calc(100vh - 100px - 211px)' }}
          onZoomEnd={(evt) => setViewState(evt.viewState)}
          mapStyle={mapStyle}
          onClick={(evt) => console.log('evt: ', evt)}
        >
          {clusters.length > 0 && renderClusters()}
        </Map>
      </div>
    </div>
  );
}
